package com.happy.xiao.consumer.callback.rabbitmq;

import com.fasterxml.jackson.core.type.TypeReference;
import com.happy.xiao.common.base.MyErrorException;
import com.happy.xiao.common.rabbitmq.bean.MessageReliabilityConfirm;
import com.happy.xiao.common.rabbitmq.BaseConsumerListener;
import com.happy.xiao.common.rabbitmq.util.MessageUtil;
import com.happy.xiao.common.rabbitmq.db.entity.MessageLog;
import com.happy.xiao.common.rabbitmq.db.service.IMessageLogService;
import com.happy.xiao.common.utils.StringUtil;
import com.happy.xiao.common.utils.Util;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 可靠性【消费确认队列监听】
 */

@Component("ReliabilityConfirmListener")
public class ReliabilityConfirmListener extends BaseConsumerListener implements ChannelAwareMessageListener {

    @Autowired
    IMessageLogService iMessageLogService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String redisPrefix = "rabbitmq-reliability-confirm-";
        try {
            System.out.println("可靠性 确认队列 =====  " + StringUtil.time());

            String messageContent = MessageUtil.getMessageContent(message);

            MessageReliabilityConfirm bean = Util.JsonToObject(new TypeReference<MessageReliabilityConfirm>() {
            }, messageContent);

            String messageId = bean.getMessageId();
            String content = bean.getContent();
            String exchange = bean.getExchange();
            String routingKey = bean.getRoutingKey();
            int delayTime = bean.getDelayTime();

            MessageLog messageLog = new MessageLog(messageId, content, exchange, routingKey,
                    String.valueOf(delayTime), StringUtil.time());
            MessageLog add = iMessageLogService.add(messageLog);

            if (add == null) throw new MyErrorException("消息消费数据失败");

            handleSuccessMessage(channel, message, redisPrefix);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: 这里要用缓存控制一下，重入队列
            // 先判断redis中，是否存在着个异常消息次数，如果不存在，则添加到redis
            // 判断redis中的次数，如果超过一定的次数，如10次，则把这个消息丢弃
            handleErrorMessage(channel, message, redisPrefix, 7);
        }
    }
}
